/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.networking

import cool.taomu.software.fig.crypto.Base64
import java.util.Map
import org.jsoup.Connection
import org.jsoup.Jsoup

class Requests {
	Connection connection

	def static void main(String[] args) {
		var req = new Requests().get("https://blog.csdn.net/z834410038/article/details/62891266")
		var resp = req.execute
		println(resp.charset)
		println(resp.statusCode)
		println(resp.url)
		println(resp.cookies)
		// println(req.body)
		println(resp.header("content-type"))
	}

	def headers(Map<String, String> headers) {
		if (headers !== null) {
			for (kv : headers.entrySet) {
				this.connection.header(kv.key, kv.value)
			}
		}
		return this
	}

	def params(Map<String, String> params) {
		if (params !== null) {
			for (kv : params.entrySet) {
				this.connection.data(kv.key, kv.value)
			}
		}
		return this
	}

	def auth(String auth) {
		if (auth !== null) {
			this.connection.header("Authorization", new String(new Base64(auth.bytes).encode, "UTF-8"))
		}
		return this;
	}

	def proxy(String host, int port) {
		this.connection.proxy(host, port)
		return this;
	}

	def execute() {
		return this.connection.execute
	}

	def get(String url) {
		return this.request("get", url)
	}

	def post(String url) {
		return this.request("post", url);
	}
	
	def put(String url){
		return this.request("put", url);
	}
		
	def delete(String url){
		return this.request("delete", url);
	}
	
	def ignoreContentType(boolean b){
	   this.connection.ignoreContentType(b);
	   return this;
	}

	def getConnection(){
	    return this.connection;
	}

	def request(String method, String url) {
		this.connection = Jsoup.connect(url)
		this.connection.header("method", method)
		return this
	}
}
